package cn.kwq.pcsystem.concurrent;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * Created with IntelliJ IDEA.
 * 异步工作线程
 *
 * @Author: kwq
 * @Date: 2023/03/06/0:32
 * @Description:
 */
@Data
@Slf4j
public class ConcurrentJobThreadUtils {

    public static void doJob(JobThreadConfig config, ExecutorService executorService){
        //获取配置
        Runnable job=config.getJob();
        String jobName= config.getJobName();
        int tryTimes=config.getTryTimes();
        long delay=config.getDelay();
        //检测配置是否合规
        Assert.isTrue(tryTimes > 0, "重试次数需要大于0");
        Assert.isTrue(delay >= 0 , "延时（毫秒）需要大于或等于0");
        Assert.isTrue(!StrUtil.isBlank(jobName) , "任务名字不能为空");
        //生成判断线程来运行任务
        JudgeThread judge=new JudgeThread();
        judge.setJob(job);
        //观察线程，观察和执行重试
        Runnable watch=()->{
            Future<Boolean> future;
            int hasTry = 0;
            boolean success =false;
            //判断剩余重试次数
            while(hasTry<tryTimes){
                //使用线程池运行
                future = executorService.submit(judge);
                try {
                    if (future.get()) {
                        //执行成功跳出循环
                        success = true;
                        break;
                    }else {
                        //执行失败进行操作
                        hasTry ++;
                        log.info("{}执行失败，第 {} 次重试 ",jobName, hasTry);
                        Thread.sleep(delay);
                    }
                } catch (ExecutionException | InterruptedException e) {
                    e.printStackTrace();
                }
            }
            log.info("{}执行完成，success：{}，重试次数：{}",jobName, success, hasTry);
        };
        //使用线程池运行
        executorService.submit(watch);
    }

}
